package com.deep.deepenterprise.api.interceptor;


import com.deep.deepenterpise.common.DrGson;
import com.deep.deepenterpise.common.code.DrCodeMsg;
import com.deep.deepenterpise.common.result.DrResult;
import com.deep.deepenterpise.common.util.DrCommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * @Auth xyz
 * @Desc //TODO 全局异常处理
 * @Time 08:49 2024/4/18
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class DrExceptionAdvice {
    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO 对参数校验失败的异常进行处理
     * @Time 08:50 2024/4/18
     * @Param [e]
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public String handleValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        log.error("[校验异常]-------" + result);
        return DrGson.toJSONString(DrResult.error(DrCodeMsg.VALID_ERR)
                .message(result.getFieldErrors().get(0).getDefaultMessage()));
    }

    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO 对参数校验失败的异常进行处理
     * @Time 08:50 2024/4/18
     * @Param [e]
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public String handleConstraintViolation(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        ConstraintViolation<?> firstViolation = constraintViolations.iterator().next();

        // 获取属性路径
        String propertyPath = firstViolation.getPropertyPath().toString();
        int index = DrViolationExceptionHandler.getIndexFromViolation(propertyPath);
        // 获取错误信息
        String message = index < 0 ? firstViolation.getMessage()
                : firstViolation.getMessage() + "，请检查第" + (index + 1) + "条记录";
        log.error("[校验异常]-------" + DrCommonUtil.drGetStackTraceInfo(e));
        return DrGson.toJSONString(DrResult.error(DrCodeMsg.VALID_ERR)
                .message(message));
    }

    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO 对未知异常进行处理，并返回系统繁忙的错误信息
     * @Time 08:50 2024/4/18
     * @Param [e]
     */
    @ExceptionHandler(value = Exception.class)
    public String handleException(Exception e) {
        log.error("[未知异常]-------" + DrCommonUtil.drGetStackTraceInfo(e));
        return DrGson.toJSONString(DrResult.error(DrCodeMsg.SYSTEM_BUSY_ERR));
    }
}
